package com.dwj.auto.comment.controller;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import com.dwj.auto.comment.common.response.Response;
import com.dwj.auto.comment.common.utils.CodeUtil;
import com.dwj.auto.comment.common.utils.RedisCacheUtil;
import com.dwj.auto.comment.model.req.AutoCommentReq;
import com.dwj.auto.comment.model.req.ExportData;
import com.dwj.auto.comment.model.vo.AutoCommentVo;
import com.dwj.auto.comment.service.IAutoCommentService;
import com.google.common.collect.Lists;
import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.*;
import org.apache.poi.xwpf.usermodel.BreakType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName AutoCommentController
 * @Description 自动生成评语控制类
 * @Author dwjian
 * @Date 2020/2/9 11:01
 */

@RestController
@RequestMapping("/api/comment")
public class AutoCommentController {

    @Resource
    private IAutoCommentService autoCommentService;

    @PostMapping("/auto")
    public Response<List<AutoCommentVo>> autoComment(@RequestBody List<AutoCommentReq> reqList) {
        return autoCommentService.autoComment(reqList);
    }

    @ResponseBody
    @RequestMapping("/exportInit")
    public Response<String> exportFile(@RequestBody List<ExportData> data) {
        if (!CollectionUtils.isEmpty(data)) {
            String key = CodeUtil.uuid();
            RedisCacheUtil.set(key, data);
            Response<String> response = Response.success();
            response.setData(key);
            return response;
        }
        return Response.fail("数据不能为空");
    }

    @RequestMapping("/export/excel/{key}")
    public void excelExport(HttpServletResponse response, @PathVariable String key) throws Exception {
        List<ExportData> exportData = RedisCacheUtil.get(key, List.class);
        if (!CollectionUtils.isEmpty(exportData)) {
            RedisCacheUtil.delete(key);
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("学生评语.xls").getBytes(), StandardCharsets.ISO_8859_1));
            WritableWorkbook workbook = Workbook.createWorkbook(response.getOutputStream());
            WritableSheet sheet = workbook.createSheet("学生评语", 0);

            WritableFont headerFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD,
                    false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            WritableCellFormat headerFormat = new WritableCellFormat(headerFont);
            // 文字垂直居中对齐
            headerFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            // 文字水平居中对齐
            headerFormat.setAlignment(jxl.format.Alignment.CENTRE);
            sheet.addCell(new Label(0, 0, "序号", headerFormat));
            sheet.addCell(new Label(1, 0, "姓名", headerFormat));
            sheet.addCell(new Label(2, 0, "评语", headerFormat));
            sheet.setRowView(0, 380);

            WritableFont delFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD,
                    false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            WritableCellFormat defFormat = new WritableCellFormat(delFont);
            // 文字垂直居中对齐
            defFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            defFormat.setWrap(true);
            try {
                for (int i = 0, j = 1; i < exportData.size(); i++, j++) {
                    ExportData exportDataItem = exportData.get(i);
                    //设置列宽
                    sheet.setColumnView(i, 16);
                    //重新设置部分列宽
                    sheet.setColumnView(0, 8);
                    sheet.setColumnView(1, 12);
                    sheet.setColumnView(2, 80);
                    //设置行高
                    sheet.getRowView(j).setAutosize(true);
                    sheet.addCell(new Label(0, j, exportDataItem.getSerial().toString(), defFormat));
                    sheet.addCell(new Label(1, j, exportDataItem.getStuName(), defFormat));
                    sheet.addCell(new Label(2, j, exportDataItem.getComment(), defFormat));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            workbook.write();
            workbook.close();
        }
    }

    @RequestMapping("/export/word/{key}")
    public void wordExport(HttpServletResponse response, @PathVariable String key) throws Exception {
        List<ExportData> exportData = RedisCacheUtil.getList(key, ExportData.class);
        if (!CollectionUtils.isEmpty(exportData)) {
            RedisCacheUtil.delete(key);
            //获取分割后的集合
            List<List<ExportData>> groupList = Lists.partition(exportData, 8);
            NiceXWPFDocument tempDoc = null;
            for (int i = 0; i < groupList.size(); i++) {
                Map<String, String> docData = new HashMap<>();
                for (int j = 0; j < groupList.get(i).size(); j++) {
                    docData.put("name" + (j + 1), groupList.get(i).get(j).getStuName() + "同学：");
                    docData.put("comment" + (j + 1), groupList.get(i).get(j).getComment());
                }
                //获取模板
                XWPFTemplate template = XWPFTemplate.compile(this.getClass().getResourceAsStream("/static/template/template_8.docx"));
                template.render(docData);
                if(i == 0){
                    tempDoc = template.getXWPFDocument();
                }else {
                    //分页
                    tempDoc.getXWPFDocument().createParagraph().createRun().addBreak(BreakType.PAGE);
                    //合并
                    tempDoc = tempDoc.merge(template.getXWPFDocument());
                }
            }
            if(tempDoc != null){
                ByteArrayOutputStream outputStream = null;
                OutputStream responseOutputStream = null;
                try {
                    outputStream = new ByteArrayOutputStream();
                    tempDoc.write(outputStream);
                    responseOutputStream = response.getOutputStream();
                    response.setHeader("Content-disposition", "attachment;filename=" + new String(("学生评语.docx").getBytes(), StandardCharsets.ISO_8859_1));
                    response.setContentType("application/octet-stream");
                    responseOutputStream.write(outputStream.toByteArray());
                    responseOutputStream.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if(outputStream != null){
                        outputStream.close();
                    }
                    if(responseOutputStream != null){
                        responseOutputStream.close();
                    }
                    tempDoc.close();
                }
            }
        }
    }
}
